import json

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseForbidden
from django.shortcuts import render

# Create your views here.
import re

from django_redis import get_redis_connection
from fdfs_client.client import Fdfs_client
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# class LoginView(APIView):
#     def post(self, request):
#         data = request.data
#         mobile = data.get('mobile')
#         password = data.get('password')
#         if not all([mobile, password]):
#             return Response({'errmsg': '参数不全', 'errno': 9999})
#         user = authenticate(request, username=mobile, password=password)
#         if user:
#             login(request, user)
#         else:
#             return Response({'errmsg': '密码错误', 'errno': 9999})
#         response = Response({'errno': 0, 'errmsg': '登陆成功'})
#         # 按照默认配置,保存两周
#         request.session.set_expiry(None)
#         response.set_cookie('username', user.mobile, expires=3600 * 24 * 7)
#         # 4.返回响应
#         return response
from users import serializers
from users.models import User


class RegisterView(APIView):
    def post(self, request):
        mobile = request.data.get("mobile")
        phonecode = request.data.get("phonecode")
        password = request.data.get("password")
        # 2, 校验数据
        if not all([mobile, phonecode, password]):
            return HttpResponseForbidden('参数不全')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('密码格式不正确')
        if not re.match(r'^1[3456789]\d{9}$', mobile):
            return HttpResponseForbidden('手机号格式不正确')
        # todo:这里需要验证短信验证码
        # 取redis中的sms_code
        # # 获取redis客户端
        redis_client = get_redis_connection('verify_code')
        redis_sms_code = redis_client.get(mobile)
        if redis_sms_code:
            redis_sms_code = redis_sms_code.decode()
        if phonecode != redis_sms_code:
            return HttpResponseForbidden('短信验证码错误')
        # 3, 处理业务
        try:
            user = User.objects.create_user(
                password=password,
                mobile=mobile,
                username=mobile
            )
        except Exception as e:
            print(e)
            return HttpResponseForbidden('用户创建失败')
        # 4, 响应结果
        return Response({"errno": "0", "errmsg": "注册成功"})


class LoginView(APIView):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 4, 返回响应
            response = Response({
                "errno": "0",
                "errmsg": "已登录",
                "data": {
                    "name": user.mobile,
                    "user_id": user.id
                }
            })
            return response
        return Response({
            "errno": "4101",
            "errmsg": "未登录"
        })

    def post(self, request):
        mobile = request.data.get("mobile")
        password = request.data.get("password")
        # 2, 校验数据
        if not all([mobile, password]):
            return HttpResponseForbidden('参数不全')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('密码格式不正确')
        if not re.match(r'^1[3456789]\d{9}$', mobile):
            return HttpResponseForbidden('手机号格式不正确')
        # 通过 authenticate() 方法 验证用户名和密码
        from django.contrib.auth import authenticate
        user = authenticate(request, username=mobile, password=password)
        if user:
            # 使用  django.contrib.auth.login  函数来登录用户
            login(request, user)
            print(user.mobile)
        # 需要保存用户登录状态
        response = Response({'errno': 0, 'errmsg': '登陆成功'})
        # 按照默认配置,保存两周
        request.session.set_expiry(None)
        # 4.返回响应
        return response

    def delete(self, request):
        # 直接登出用户
        logout(request)
        response = Response({'errno': 0, 'errmsg': '登陆成功'})
        # 通过响应对象, 向浏览器发送删除cookie的指令
        response.delete_cookie('mobile')
        return response


class UserInfoView(APIView):
    def get(self, request):
        user = request.user
        avatar = ''
        if user.avatar:
            avatar = user,avatar.url
        res = {"data": {
                "avatar": avatar,
                "create_time": user.date_joined,
                'user_id': user.id,
                "mobile": user.mobile,
                "name": user.username,
            },
            "errmsg": "OK",
            "errno": "0"
        }
        return Response(res)


class ModifyUserView(APIView):
    def put(self, request):
        dict_data = json.loads(request.body.decode())
        username = dict_data.get("name")
        user = request.user
        try:
            user.username = username
            user.save()
        except Exception as e:
            print(e)
            return Response({"errno": 404, "errmsg": "修改失败"})
        return Response({"errno": 0, "errmsg": "修改成功"})


class UserIdView(APIView):
    def get(self, request):
        user = request.user
        # 判断用户是否已经实名完成
        try:
            user_data = User.objects.get(mobile=user.mobile)
        except Exception as e:
            return Response({"errno": "4101", "errmsg": "用户不存在，请重新登录"})
        data = {"real_name": user_data.real_name, "id_card": user_data.id_card}
        return Response({"errno": "0", "data": data})

    def post(self, request):
        user = request.user
        # 判断用户是否已经实名完成
        try:
            user_data = User.objects.get(mobile=user.mobile)
        except Exception as e:
            return Response({"errno": "4101", "errmsg": "用户不存在，请重新登录"})
        # 获取数据
        data = request.data
        real_name = data.get('real_name')
        id_card = data.get('id_card')
        # 校验参数
        # 1,校验信息完整
        if not all([real_name, id_card]):
            return Response({"errno": "9999", "errmsg": "参数不全，请重新输入"})
        # 2,校验身份证信息
        if not re.match(r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$',
                        id_card):
            return Response({"errno": "9999", "errmsg": "身份证格式不正确"})
        # 数据入库
        User.objects.filter(mobile=user.mobile).update(id_card=id_card, real_name=real_name)
        return Response({
            "errno": "0",
            "errmsg": "认证信息保存成功"
        })


class UserImageView(GenericAPIView):
    queryset = User.objects.all()
    serializer_class = serializers.UserImageSerializer

    def post(self, request):
        user = request.user
        avatar = request.FILES.get('avatar')
        try:
            user_data = User.objects.get(mobile=user.mobile)
        except Exception as e:
            return Response({"errno": '9999', "errmsg": "用户不存在"})
        client = Fdfs_client('/home/python/Desktop/ihome_project/ihome_project/ihome/utils/fdfs/client.conf')
        result = client.upload_by_buffer(avatar.read())
        if result['Status'] != 'Upload successed.':
            return Response({"errno": "9999", "errmsg": "图片上传失败"})
        image_url = result["Remote file_id"]  # 取出图片url
        user_data.avatar = image_url
        user_data.save()
        avatar_url = settings.BASE_URL + image_url
        return Response({
            "data": {"avatar_url": avatar_url},
            "errno": "0",
            "errmsg": "头像上传成功"
        })
